package info.xiaolong.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @Classname ThreadPoolUtil
 * @Description 线程池工具
 * @Date 2021/12/8 14:50
 * @Created by xiaolongoba
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    /*这里线程池的配置可以采用@value注入形式也可以使用常量,@value的形式更加灵活,更推荐一些*/
    @Value("${baseThreadPool.corePoolSize:5}")
    private Integer corePoolSize ; // 核心线程数
    @Value("${baseThreadPool.maxPoolSize:10}")
    private Integer maxPoolSize ;   //最大线程数
    @Value("${baseThreadPool.queueCapacity:20}")
    private Integer queueCapacity ; // 缓冲队列容量
    @Value("${baseThreadPool.keepAliveSeconds:60}")
    private Integer keepAliveSeconds ; //线程存活时间
    @Value("${baseThreadPool.waitForTask:true}")
    private Boolean waitForTask ; // 线程池关闭策略

    @Bean(name = "baseThreadPool")
    public ThreadPoolTaskExecutor baseThreadPool (){
        /*核心参数配置*/
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(waitForTask);
        /*设置拒绝策略*/
        //threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        /*设置线程池前缀*/
        threadPoolTaskExecutor.setThreadNamePrefix("baseThreadPool");
        threadPoolTaskExecutor.initialize();
        System.out.println("线程池初始化");
        return threadPoolTaskExecutor ;
    }

}
